mui.init();

//测试屏幕左右滑动
document.addEventListener("swipeleft", function () {
    console.log('前往下一题');
    var dataObj = brushing_data;
    var m = dataObj.q_index + 1;
    if (m == dataObj.other.count_num) {
        mui.toast('已经是最后一题咯！', {duration: 1500,type: 'div'});
        return false;
    } else if (dataObj.yes_num != 300 && dataObj.an == 0) {
        mui.toast('您还有答案未提交，请提交之后再切换题目！', {duration: 1500,type: 'div'});
        return false;
    } else {
        dataObj.record_answer();
        dataObj.q_index++; //翻到下一题
    }

});
document.addEventListener("swiperight", function () {
    console.log('返回上一题');
    var dataObj = brushing_data;
    if (dataObj.q_index == 0) {
        mui.toast('已经是第一题咯！', {duration: 1500,type: 'div'});
        return false;
    } else if (dataObj.yes_num != 300 && dataObj.an == 0) {
        mui.toast('您还有答案未提交，请提交之后再切换题目！', {duration: 1500,type: 'div'});
        return false;
    } else {
        dataObj.record_answer();
        dataObj.q_index--;
    }
});


var brushing_data;
mui.plusReady(function () {
	//禁用ios右滑返回
    plus.webview.currentWebview().setStyle({ 'popGesture': 'none' });
    plus.navigator.setStatusBarStyle('dark');
    var self = plus.webview.currentWebview();
    var catid = self.catid;
    brushing_data = new Vue({
        el: '#questions_box',
        data: {
            questionBoxStatus:0,
            questionErrorBoxStatus:0,
            errorTipsContent:"数据加载失败，可能网络异常",
            other: '',
            question_list: '',
            q_index: 0, //题目下标
            collection_status: 0,
            category: 30,
            question_id: '', //题目ID
            userAnswer: [], //用户答题记录,该数组记录是否已经点击过提交按钮
            Answering: [], //记录用户答案 用于在前后翻页时能够显示已经回答的答案

            cailiao_userAnswer: [], //记录材料题用户答题是否已经点击过提交按钮
            cailiao_Answering: [], //记录材料题用户答题记录 用于翻页时显示用户已作答的答案
            an: 0, //0表示该题目未提交过  1表示已经提交过,
            myAnswer: '', //用来显示用户已经填写提交过的答案
            myan: '', //用户填写答案的文本域双向绑定数据
            yes_num: 300,
            cailiaoTab: 0, //材料题切换选项卡的选项卡ID
            cailiaoCate: 'cailiao', //材料题切换选项卡的选项卡类型
            cailiao_question_id: '', //材料题问题的ID
            cailiao_question_parent_id: '', //材料题问题的对应材料ID
            wenti_index: 0,
            dtk_but_status: 1,
        },
        mounted() {
            this.getQuestionsLists();
        },
        watch: {
            wenti_index: function (val, oldVal) {
                //记录切换之前那个下标问题的数据
                if (this.cailiao_userAnswer[oldVal] == 0) {
                    if (this.yes_num == 300) {
                        //表示用户没有输入任何文字
                        this.cailiao_userAnswer.splice(oldVal, 1, 0);
                    } else {
                        //用户输入过文字但是没有点击提交按钮
                        if (this.an == 0) {
                            this.cailiao_userAnswer.splice(oldVal, 1, 0);
                        } else {
                            //点击过提交按钮
                            this.cailiao_userAnswer.splice(oldVal, 1, 1);
                        }
                        this.cailiao_Answering[oldVal].splice(2, 1, this.myan);
                    }
                }

                //设置切换之后问题的回答
                if (val != -1) {
                    if (this.cailiao_userAnswer[val] == 1) {
                        this.myAnswer = this.cailiao_Answering[val][2];
                        this.an = 1;
                        this.myan = this.cailiao_Answering[val][2];
                    } else {
                        if (this.cailiao_Answering[val]) {
                            this.myan = this.cailiao_Answering[val][2];
                        } else {
                            this.myan = '';
                        }
                        this.myAnswer = '';
                        this.an = 0;
                    }
                }

                console.log(this.cailiao_userAnswer);
                console.log(this.cailiao_Answering);
            },
            q_index: function (val, oldVal) {
                if (val == this.other.count_num) {
                    mui.toast('已经是最后一题咯！', {
                        duration: 1500,
                        type: 'div'
                    });
                    return false;
                }
                this.category = this.question_list[val].category;
                this.question_id = this.question_list[val].id;
                this.collection_status = this.question_list[val].collection_status;
                this.an = this.userAnswer[val];
                if (this.category == 50) {
                    this.cailiaoTab = this.question_list[val]['cl_li'][0].cailiao_index;
                    this.cailiaoCate = 'cailiao';
                    this.cailiao_question_id = this.question_list[val]['question_li'][this.cailiaoTab].id;
                }
                if (this.category == 30) {
                    if (this.userAnswer[val] == 1) {
                        this.myAnswer = this.Answering[val][2];
                        this.myan = this.Answering[val][2];
                        this.an = 1;
                    } else {
                        this.myAnswer = '';
                        this.myan = '';
                        this.an = 0;
                    }
                }
            },
            myan: function () {
                var str = this.myan;
                var len = str.replace(/[\u0391-\uFFE5]/g, "aa").length;
                this.yes_num = 300 - len;
            },
        },
        methods: {
            clickRefresh:function(){
                this.getQuestionsLists();
            },
            getQuestionsLists: function () {
                showWatting();
                var self = this;
                var api_host = plus.storage.getItem('HOST_URL');
                mui.ajax({
                    url: api_host + '/api/questionbank/choice_question/brushing_questions',
                    data: {
                        'catid': catid,
                        'type': 'zg',
                    },
                    headers:{'User-Token':plus.storage.getItem('UserToken')},
                    timeout:3000,
                    dataType: 'json',
                    type: 'get',
                    success: function (msg) {
                        if (msg.code == 1) {
                            console.log(msg.data);
                            self.questionErrorBoxStatus = 0;
                            self.questionBoxStatus = 1;
                            self.question_list = msg.data.question;
                            self.category = self.question_list[0].category;
                            self.question_id = self.question_list[0].id;
                            self.collection_status = self.question_list[0].collection_status;
                            self.other = msg.data.other;
                            var c = self.other.count_num;
                            for (var i = 0; i < c; i++) {
                                self.userAnswer.splice(i, 1, 0);
                            }
                            var d = self.other.count_question_num;
                            for (var j = 0; j < d; j++) {
                                self.cailiao_userAnswer.splice(j, 1, 0);
                                self.cailiao_Answering.splice(j, 1, 0);
                            }
                        } else {
                            self.questionErrorBoxStatus = 1;
                            self.questionBoxStatus = 0;
                            self.errorTipsContent = msg.msg;
                            mui.toast(msg.msg, {duration: '200',type: 'div'});
                        }
                    },
                    error: function (xhr, type, errorThrown) {
                        self.questionErrorBoxStatus = 1;
                        mui.toast('加载失败!', {duration: '200',type: 'div'});
                    },
                    complete: function () {
                        plus.nativeUI.closeWaiting();
                    }
                });
            },
            record_answer: function () {
                //记录用户答题
                console.log(this.myan);
                if (this.category == 30) {
                    if (this.yes_num == 300) {
                        this.userAnswer.splice(this.q_index, 1, 0);
                    } else {
                        this.userAnswer.splice(this.q_index, 1, 1);
                    }

                    if (this.Answering[this.q_index]) {
                        this.Answering[this.q_index].splice(2, 1, this.myan);
                    } else {
                        var ans = [this.category, this.question_id, this.myan]
                        this.Answering.push(ans);
                    }
                    console.log(this.userAnswer);
                    console.log(this.Answering);
                } else if (this.category == 50) {
                    if (this.cailiao_userAnswer[this.cailiaoTab] == 1) {
                        this.userAnswer.splice(this.q_index, 1, 1);
                    } else {
                        this.userAnswer.splice(this.q_index, 1, 0);
                    }
                    console.log(this.cailiao_userAnswer);
                    console.log(this.cailiao_Answering);
                }
            },
            tijiao_zuoda: function (type) {
                //简答题单个题目答案提交
                if (this.yes_num == 300) {
                    mui.toast('您还没有作答，无法提交哦！', {
                        duration: 1500,
                        type: 'div'
                    });
                    return false;
                } else {
                    // submit_question_answer(type,catid);
                    if (type == 'j') {
                        this.an = 1;
                        this.myAnswer = this.myan;
                        this.userAnswer.splice(this.q_index, 1, 1);
                        if (this.Answering[this.q_index]) {
                            this.Answering[this.q_index].splice(2, 1, this.myan);
                        } else {
                            var ans = [this.category, this.question_id, this.myan];
                            this.Answering.push(ans);
                        }
                        console.log(this.userAnswer);
                        console.log(this.Answering);
                    } else if (type == 'c') {
                        this.an = 1;
                        this.myAnswer = this.myan;
                        this.cailiao_userAnswer.splice(this.cailiaoTab, 1, 1);
                        if (this.cailiao_Answering[this.cailiaoTab]) {
                            this.cailiao_Answering[this.cailiaoTab].splice(2, 1, this.myan);
                        } else {
                            var ans = [this.category, this.cailiao_question_id, this.myan, this.question_id];
                            this.cailiao_Answering.splice(this.cailiaoTab, 1, ans);
                        }
                        console.log(this.cailiao_userAnswer);
                        console.log(this.cailiao_Answering);
                    }
                }

            },
            select_cailiaoTab: function (e) {
                if (e.target.getAttribute('tabCat') == 'wenti') {
                    this.cailiaoTab = e.target.getAttribute('qINdex');
                    this.cailiao_question_id = e.target.getAttribute('qid');
                    this.wenti_index = e.target.getAttribute('qINdex');
                } else if (e.target.getAttribute('tabCat') == 'cailiao') {
                    this.cailiaoTab = e.target.getAttribute('cINdex');
                    this.wenti_index = -1;
                }
                this.cailiaoCate = e.target.getAttribute('tabCat');

                console.log(this.cailiao_userAnswer);
                console.log(this.cailiao_Answering);
            },
            tiaozhuan_que: function (ind) {
                //点击答题卡小圆球跳转题目
                this.q_index = ind;
                this.yc_dtk();
            },
            open_dtk: function () {
                //显示答题卡
                $('.popMask').show();
                $('.popCard').animate({
                    'bottom': '0%'
                }, 300).show();
            },
            yc_dtk: function () {
                //隐藏答题卡
                $('.popMask').hide();
                $('.popCard').animate({
                    'bottom': '-100%'
                }, 300).hide(300);
            },
            add_collection: function () {
                questionCollection(this.question_id, this.question_list[this.q_index]['category'],brushing_data);
            },
            open_jc: function () {
                //打开纠错界面
                mui.openWindow({
                    url: 'errorCorrection.html',
                    extras: {
                        'question_id': this.question_id,
                        'category': this.question_list[this.q_index]['category']
                    },
                    createNew: false,
                    show: {
                        autoShow: true,
                        aniShow: 'pop-in',
                        duration: 400
                    },
                    waiting: {
                        autoShow: false,
                    }
                })
            },
            tijiaojieguo: function () {
                 var self = this;
                //提交并查看结果
                $('.popMask').hide();
                $('.popCard').animate({
                    'bottom': '-100%'
                }, 300).hide(300);
                plus.nativeUI.showWaiting('正在提交中...');
                batch_zg_question_post(catid);
                setTimeout(function () {
                    self.q_index = 0;
                    self.dtk_but_status = 0;
                    var len = self.userAnswer.length;
                    for (var i = 0; i < len; i++) {
                        self.userAnswer.splice(i, 1, 1);
                    }
                    var l = self.cailiao_userAnswer.length;
                    for (var j = 0; j < l; j++) {
                        self.cailiao_userAnswer.splice(j, 1, 1);
                    }
                    plus.nativeUI.closeWaiting();
                    console.log(self.userAnswer);
                    console.log(self.cailiao_userAnswer);
                }, 1000)
            },
            back_but: function () {
                //用户点击返回
                var btnArray = ['继续作答', '退出'];
                mui.confirm('当前练习未完成，退出将不会保存本次练习记录，确定退出？', '警告', btnArray, function (e) {
                    if (e.index == 0) {
                        mui.toast('取消退出', {duration: 1500,type: 'div'});
                    } else {
                        mui.openWindow({
                            url: '../columns/questionBank.html',
                            createNew: false,
                            show: {
                                autoShow: true,
                                aniShow: 'pop-in',
                                duration: 400
                            },
                            waiting: {
                                autoShow: false,
                            }
                        })
                    }
                })
            }
        }
    })
});

//主观题批量提交
function batch_zg_question_post(catid) {
    var api_host = plus.storage.getItem('HOST_URL');
    mui.ajax({
        url: api_host + '/api/questionbank/choice_question/zg_batch_post',
        data: {
            'catid': catid,
            'jianda_answer': brushing_data.Answering,
            'cailiao_answer': brushing_data.cailiao_Answering,
        },
        dataType: 'json', //服务器返回json格式数据
        type: 'post', //HTTP请求类型
        headers:{'User-Token':plus.storage.getItem('UserToken')},
        timeout: 10000, //超时时间设置为10秒；
        success: function (msg) {
            mui.toast(msg.msg, {duration: '1000',type: 'div'});
        },
        error: function (xhr, type, errorThrown) {
            mui.toast('提交出错', {duration: '1000',type: 'div'});
        }
    });
}

var backButtonPress = 0;
mui.back = function(event) {
    backButtonPress++;
    if (backButtonPress > 1) {
        setTimeout(function(){
            plus.webview.currentWebview().close();
        }, 100)
    } else {
        plus.nativeUI.toast('再按一次退出答题');
    }
    setTimeout(function() {
        backButtonPress = 0;
    }, 2000);
    return false;
};


//简答题单个答案提交
/*function submit_question_answer(type,catid) {
    var api_host = plus.storage.getItem('HOST_URL');
    var userInfo = JSON.parse(plus.storage.getItem('userInfo'));
    var user_token = plus.storage.getItem('user_token');
    if(type == 'j'){
    	var qid = brushing_data.question_id;  //题目的ID
    	var children_id = ''; //如果是材料题  就是这个问题的ID
	}else if(type == 'c'){
        var qid = brushing_data.question_id;
        var children_id = brushing_data.cailiao_question_id;
	}
    mui.ajax({
        url:api_host+'/api/questionbank/choice_question/zg_question_ones_answer',
        data:{
        	'userToken':user_token,
			'mobile':userInfo.mobilenum,
			'question_id':qid,
			'children_id':children_id,
            'question_answer':brushing_data.myan,
			'category':2,
			'category_id':catid,
			'question_category':brushing_data.category,
		},
        dataType:'json',//服务器返回json格式数据
        type:'post',//HTTP请求类型
        timeout:10000,//超时时间设置为10秒；
        success:function(msg){
            mui.toast(msg.msg,{ duration:'1000', type:'div'});
        	if(msg.code == 1){
                brushing_data.an = 1;
                brushing_data.myAnswer = brushing_data.myan;
                brushing_data.userAnswer.splice(brushing_data.q_index,1,1);
                if(brushing_data.Answering[brushing_data.q_index]){
                    brushing_data.Answering[brushing_data.q_index].splice(2,1,brushing_data.myan);
                }else{
                    var ans = [brushing_data.category,brushing_data.question_id,brushing_data.myan];
                    brushing_data.Answering.push(ans);
                }
			}else{
                brushing_data.an = 0;
			}
        },
        error:function(xhr,type,errorThrown){
            mui.toast('系统错误，请联系客服！',{ duration:'2000', type:'div'});
        }
    });
}*/
